package controllers

import (
	"github.com/astaxie/beego"
	"shuxianghui/models"
	"HTshuxianghui/htmodels"
	"strconv"
	"time"
	"os"
	"strings"
	"github.com/astaxie/beego/validation"
	"fmt"
	"encoding/base64"
	"io/ioutil"
	"github.com/Terry-Mao/paint/wand"
	"github.com/Terry-Mao/paint"
	"log"
)

type ArticleController struct {
	beego.Controller
}

func (c *ArticleController)Prepare() {
	level := c.GetSession("utype")
	if level == nil {
		Message(&c.Controller, `/login`, "登录信息错误", "", false)
	}
	c.Data["utype"] = level.(int)
	tacleArticlePermission(c, level.(int))
}

//带了参数导致bootstrap table无法正常使用
func (c *ArticleController)HTArticleList_html() {
	str_Status := c.Ctx.Input.URL()[strings.LastIndex(c.Ctx.Input.URL(), "/") + 1:]
	Status, _ := strconv.Atoi(str_Status)
	c.Data["Status"] = Status
	str1 := c.Ctx.Input.URL()[:strings.LastIndex(c.Ctx.Input.URL(), "/")]
	str_ArticleType := str1[strings.LastIndex(str1, "/") + 1:]
	ArticleType, _ := strconv.Atoi(str_ArticleType)
	c.Data["ArticleType"] = ArticleType
	c.TplName = "article_list.html"
	c.Render()
}

func (c *ArticleController)HTArticleDushuList() {
	c.Data["Status"] = 3
	c.Data["ArticleType"] = 3
	c.TplName = "dushu_list.html"
	c.Render()
}

func GetEditable(status int, level int, ArticleType int) bool {
	if level >= 100 {
		return true
	}
	if (status == 0 || status == 3) && (inPermissionB(ArticleType)) {
		if level >= 2 {
			return true
		}
	}
	if (status == 0 || status == 3) && inPermissionA(ArticleType) {
		if level >= 10 {
			return true
		}
	}
	if status == 1 {
		return true
	}
	if status == 3 && level == 10 {
		return true
	}
	return false
}

func GetEditText(status int, level int, ArticleType int) string {

	if inPermissionB(ArticleType) {
		if status == 0 {
			return "审核"
		}
		if status == 3 {
			return "编辑"
		}
	}
	if inPermissionA(ArticleType) {
		if status == 0 || status == 2 {
			return "审核"
		}
	}
	return "编辑"
}

func (c *ArticleController)HTArticleList() {
	Status, _ := c.GetInt("Status")
	ArticleType, _ := c.GetInt("ArticleType")
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{"Id", "Title", "Author", "EditTime", "Introduction", "ArticleType", "Status", "BrowseCount", "StartCount", "WatchCount", "UserId"}
	Article := []models.Article{}
	uid := 0
	if c.GetSession("utype").(int) < 2 {
		uid = c.GetSession("uid").(int)
	}
	var cityList []htmodels.CityId_int
	if c.GetSession("utype").(int) == 100 {
		cityList = getPermissionCityList(c.GetSession("uid").(int))
		if len(cityList) == 0 {
			c.Data["json"] = map[string]interface{}{"rows":&Article, "total":0}
		}
	}
	htmodels.HTArticleGetList(&Article, fileds, Status, ArticleType, offset, limit, search, "Title", orderby, c.GetSession("city").(int), uid, cityList)
	count, _ := htmodels.HTArticleGetCount(search, "Title", Status, ArticleType, c.GetSession("city").(int), uid, cityList)
	c.Data["json"] = map[string]interface{}{"rows":&Article, "total":count}
	c.ServeJSON()
}

func getPermissionCityList(uid int) (mylist []htmodels.CityId_int) {
	var MatchedList []models.City
	if err := htmodels.HTCityGetAdminCitiesByUserId(&MatchedList, uid); err != nil {
		return
	}
	for _, v := range MatchedList {
		mylist = append(mylist, htmodels.CityId_int(v.Id))
	}
	return
}

func (c *ArticleController)HTArticleSearch_html() {
	userid, _ := c.GetInt("userid")
	c.Data["User"] = userid
	c.TplName = "article_search.html"
	c.Render()
}

func (c *ArticleController)HTArticleSearch() {
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	searchFiled := c.GetString("scolumn")
	if searchFiled == "" {
		searchFiled = "Title"
	}

	Article := []models.Article{}
	if searchFiled == "Phone" {
		searchFiled = "UserId"
		search = strconv.Itoa(htmodels.GetUserIdByPhone(search))
		if search == "0" {
			c.Data["json"] = map[string]interface{}{"rows":&Article, "total":0}
		}
	}
	fileds := []string{"Id", "Title", "Author", "EditTime", "Introduction", "ArticleType", "Status", "BrowseCount", "StartCount", "WatchCount", "UserId"}
	uid := 0
	if c.GetSession("utype").(int) < 2 {
		uid = c.GetSession("uid").(int)
	}
	var cityList []htmodels.CityId_int
	if c.GetSession("utype").(int) == 100 {
		cityList = getPermissionCityList(c.GetSession("uid").(int))
		if len(cityList) == 0 {
			c.Data["json"] = map[string]interface{}{"rows":&Article, "total":0}
			c.ServeJSON()
			c.StopRun()
		}
	}
	htmodels.HTArticleGetList(&Article, fileds, -1, -1, offset, limit, search, searchFiled, orderby, c.GetSession("city").(int), uid, cityList)
	count, _ := htmodels.HTArticleGetCount(search, searchFiled, -1, -1, c.GetSession("city").(int), uid, cityList)
	c.Data["json"] = map[string]interface{}{"rows":&Article, "total":count}
	c.ServeJSON()
}

func (c *ArticleController)HTArticleDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true

		SetArticleDetailInfo(c, Id)
	} else {
		c.Data["username"] = c.GetSession("name").(string)
	}
	mytype, err := c.GetInt("type")
	fmt.Println(mytype, err)
	if err == nil {
		c.Data["Type"] = mytype
	}
	c.TplName = "article_detail.html"
}

func SetArticleDetailInfo(c *ArticleController, Id int64) {
	Article := models.Article{Id:int(Id)}
	htmodels.HTArticleGetDetail(&Article)
	tacleDeniable(c, &Article)
	c.Data["SubmitText"] = getSubmitText(Article.ArticleType, Article.Status, c.Data["utype"].(int))
	c.Data["Type"] = Article.ArticleType
	c.Data["Article"] = &Article
	if Article.ArticleType == 3 {
		c.TplName = "dushu_detail.html"
		c.Render()
		c.StopRun()
	}
}

func tacleDeniable(c *ArticleController, Article *models.Article) {
	if Article.Status == 1 {
		c.Data["deniable"] = false
		return
	}
	if inPermissionA(Article.ArticleType) {
		if Article.Status < 3 {
			if c.GetSession("utype").(int) >= 10 {
				c.Data["deniable"] = true
				return
			}
		}
	}
	if inPermissionB(Article.ArticleType) {
		if Article.Status < 3 {
			if c.GetSession("utype").(int) >= 2 {
				c.Data["deniable"] = true
				return
			}
		}
	}
	c.Data["deniable"] = false
}

func (c *ArticleController)HTArticleAdd() {
	Article := models.Article{}
	if err := c.ParseForm(&Article); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	Article.EditTime = time.Now()
	Article.CreateTime = time.Now()
	valide := validation.Validation{}
	if b, err := valide.Valid(&Article); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	Article.UserId = c.GetSession("uid").(int)
	Article.CityId = c.GetSession("city").(int)
	if err := htmodels.HTArticleAdd(&Article); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"文章《" + Article.Title + "》上传", LogTime:time.Now(), LogType:htmodels.LogType_ArticleAdd, Status:0})
	Message(&c.Controller, `/article/detail?type=` + strconv.Itoa(Article.ArticleType), "添加成功！", "", false)
}

func (c *ArticleController)HTArticleAddassistant() {
	if c.Data["utype"].(int) != 10 {
		Json_Message(&c.Controller, 1, "not permitted!")
	}
	phone := c.GetString("phone")
	if phone == "" {
		setAssistantinfo(c)
	}
	user := models.Users{Phone:phone}
	if err := htmodels.HTUserGetUserByPhone(&user); err != nil {
		Json_Message(&c.Controller, 1, "用户不存在")
	}
	user.UserType = 2;
	if user.CityId != c.GetSession("city").(int) {
		Json_Message(&c.Controller, 1, "地区不一致")
	}
	if err := htmodels.HTUsersUpdate(&user); err != nil {
		Json_Message(&c.Controller, 1, "助理添加错误")
	}
	Json_Message(&c.Controller, 0, "添加成功")
}
func (c *ArticleController)HTArticleDeleteassistant() {
	phone := c.GetString("phone")
	if phone == "" {
		Json_Message(&c.Controller, 1, "手机号不可为空")
	}
	user := models.Users{Phone:phone}
	if err := htmodels.HTUserGetUserByPhone(&user); err != nil {
		Json_Message(&c.Controller, 1, "用户不存在")
	}
	user.UserType = 1;
	if user.CityId != c.GetSession("city").(int) {
		Json_Message(&c.Controller, 1, "地区不一致")
	}
	if err := htmodels.HTUsersUpdate(&user); err != nil {
		Json_Message(&c.Controller, 1, "助理删除错误")
	}
	Json_Message(&c.Controller, 0, "删除成功")
}

func setAssistantinfo(c *ArticleController) {
	city := c.GetSession("city").(int)
	users := []models.Users{}
	if err := htmodels.HTGetUsersByCityAndType(&users, city, 2); err != nil {
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	c.Data["users"] = &users
	c.TplName = "addAssistant.html"
	c.Render()
	c.StopRun()
}

func (c *ArticleController)HTArticleUpdate() {
	Id, _ := c.GetInt64("Id");
	Article := models.Article{Id:int(Id)}
	if err := htmodels.HTArticleGetDetail(&Article); err != nil {
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	status_tmp := Article.Status
	if err := c.ParseForm(&Article); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("edittime")); err != nil {
		Article.EditTime = time.Now()
	} else {
		Article.EditTime = time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("createtime")); err != nil {
		Article.CreateTime = time.Now()
	} else {
		Article.CreateTime = time_up
	}
	Article.Status = tacleArticleStatus(c, status_tmp, Article.Status, Article.ArticleType, c.Data["utype"].(int), Article.UserId, &Article)
	valide := validation.Validation{}
	if b, err := valide.Valid(&Article); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTArticleUpdate(&Article); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	if c.GetSession("uid").(int) >= 100 {
		htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"文章《" + Article.Title + "》更新", LogTime:time.Now(), LogType:htmodels.LogType_ArticleUpdate, Status:0})
	}
	Message(&c.Controller, `/article/list_html` + `/` + strconv.Itoa(Article.ArticleType) + `/` + strconv.Itoa(Article.Status), "更新成功！", "", false)
}

func (c *ArticleController)HTArticleDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTArticleDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:c.GetString("Id"), LogTime:time.Now(), LogType:htmodels.LogType_ArticleDelete, Status:0})
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}

func (c *ArticleController)HTArticleStatusChange() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	Status, err1 := c.GetInt("ChangedStatus")
	if err1 != nil {
		Json_Message(&c.Controller, 0, "更改失败")
	}
	count, err := htmodels.HTArticleStatusChange(Ids, Status)
	if err != nil {
		Json_Message(&c.Controller, 0, "更改失败" + err.Error())
	}
	htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:c.GetString("Id"), LogTime:time.Now(), LogType:htmodels.LogType_ArticleStatusChange, Status:0})
	Json_Message(&c.Controller, 1, "更改" + strconv.FormatInt(count, 10) + "行状态")
}

func (c *ArticleController)HTArticleFengcaiChange() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	fengcai, err1 := c.GetInt("fengcai")
	if fengcai == 7 {
		fengcai = 8
	} else if fengcai == 8 {
		fengcai = 7
	}
	if err1 != nil {
		Json_Message(&c.Controller, 0, "更改失败")
	}
	count, err := htmodels.HTArticleArticleTypeChange(Ids, fengcai)
	if err != nil {
		Json_Message(&c.Controller, 0, "更改失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "更改" + strconv.FormatInt(count, 10) + "行状态")
}

//multi doc image upload
func (c *ArticleController)HTArticleMutiTextImageUp() {
	TacleUeditor(&c.Controller)
	taclescrawl(c)
	tacleVideo(c)
	f, h, err := c.GetFile("upfile")
	if err != nil {
		f.Close()
		Json_Message(&c.Controller, 1, "file upload error")
	}
	date := time.Now().Format("2006-01-02")
	filename := RandString(8)
	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	path := beego.AppConfig.String("uploadspath")
	directory := "/article/mutitext/" + date
	totalFileName := path + directory + filename + typename
	url := "/uploads" + directory + filename + typename
	os.MkdirAll(path + directory, 0777)
	f.Close()
	err = c.SaveToFile("upfile", totalFileName)
	if err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	TacleImageScale(totalFileName, 640, "")
	c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "url":  url, "name": filename + typename, "size":"1000", "originalName":  filename + typename, "type":typename}
	c.ServeJSON()
}

func tacleVideo(c *ArticleController) {
	action := c.GetString("action")
	if action != "uploadvideo" {
		return
	}
	f, h, err := c.GetFile("upfile")
	if err != nil {
		f.Close()
		Json_Message(&c.Controller, 1, "file upload error")
	}
	date := time.Now().Format("2006-01-02")
	filename := RandString(8)
	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	path := beego.AppConfig.String("uploadspath")
	directory := "/article/video/" + date
	totalFileName := path + directory + filename + typename
	url := "/uploads" + directory + filename + typename
	os.MkdirAll(path + directory, 0777)
	f.Close()
	err = c.SaveToFile("upfile", totalFileName)
	if err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "url":  url, "name": filename + typename, "size":"1000000", "originalName":  filename + typename, "type":typename}
	c.ServeJSON()
}

//func TacleImageScale(path string,width int,suffix string)  {
//	src, err := LoadImage_FromPath(path)
//	if err != nil {
//		return
//	}
//	// 缩略图的大小
//	height:=int(float64(width)*float64(float64(src.Bounds().Dy())/float64(src.Bounds().Dx())))
//	dst := image.NewRGBA(image.Rect(0, 0, width, height))
//	// 产生缩略图
//	err = graphics.Scale(dst, src)
//	if err != nil {
//		return
//	}
//	SaveImage(path+suffix, dst)
//}

func TacleImageScale(path string, width int, suffix string) {
	w := wand.NewMagickWand()
	defer w.Destroy()
	if err := w.ReadImage(path); err != nil {
		log.Printf("error when read image of path(%s) with error(%s)", path, err.Error())
		return
	}
	width_u := uint(width)
	height := uint(float64(width_u) * float64(float64(w.ImageHeight()) / float64(w.ImageWidth())))

	if err := paint.Thumbnail(w, width_u, height); err != nil {
		log.Printf("error when thumb image of path(%s) with error(%s)", path, err.Error())
		return
	}

	if err := w.WriteImage(path + suffix); err != nil {
		log.Printf("error when wright image of path(%s) with error(%s)", path, err.Error())
	}
	w.Clear()
	return
}

func taclescrawl(c *ArticleController) {
	if c.GetString("action") == "uploadscrawl" {
		data := c.GetString("content")
		data = strings.Replace(data, "data:image/png;base64,", "", 1)
		buf, _ := base64.StdEncoding.DecodeString(data) //成图片文件并把文件写入到buffer
		date := time.Now().Format("2006-01-02")
		filename := RandString(8)
		typename := "png"
		path := beego.AppConfig.String("uploadspath")
		directory := "/article/mutitext/" + date
		totalFileName := path + directory + filename + typename
		url := "/uploads" + directory + filename + typename
		os.MkdirAll(path + directory, 0777)
		err := ioutil.WriteFile(totalFileName, buf, 0666)   //buffer输出到jpg文件中（不做处理，直接写到文件）
		if err != nil {
			Json_Message(&c.Controller, 1, "file save error" + err.Error())
		}
		c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "url":  url, "name": filename + typename, "size":"1000", "originalName":  filename + typename, "type":typename}
		c.ServeJSON()
	}
}

//image upload
func (c *ArticleController)HTArticlePicUp() {
	Id, _ := c.GetInt64("Id")
	ArticleType, _ := c.GetInt("ArticleType")
	f, h, err := c.GetFile("Filedata")
	if err != nil {
		Json_Message(&c.Controller, 1, "file upload error")
	}
	url := c.GetString("imagepath")
	totalpath := ""
	path := beego.AppConfig.String("uploadspath")
	//if url == "" {
	//	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	//	date := time.Now().Format("2006-01-02")
	//	directory := "/article/pics/" + date
	//	filename := RandString(8)
	//	totalpath = path + directory + "/" + filename + typename
	//	url = "/uploads" + directory + "/" + filename + typename
	//	os.MkdirAll(path + directory, 0777)
	//} else {
	//	if strings.Index(url, "?") != -1 {
	//		url = url[:strings.Index(url, "?")]
	//	}
	//	totalpath = path + url[strings.Index(url, "uploads") + len("uploads"):]
	//}
	typename := h.Filename[strings.LastIndex(h.Filename, "."):]
	date := time.Now().Format("2006-01-02")
	directory := "/article/pics/" + date
	filename := RandString(8)
	totalpath = path + directory + "/" + filename + typename
	url = "/uploads" + directory + "/" + filename + typename
	os.MkdirAll(path + directory, 0777)
	f.Close()

	if err := c.SaveToFile("Filedata", totalpath); err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	TacleArticleTumbnail(totalpath, Id, ArticleType)
	Json_Message(&c.Controller, 0, url + "?time=" + time.Now().String())
}

func TacleArticleTumbnail(totalpath string, Id int64, ArticleType int) {
	TacleImageScale(totalpath, 160, "_160.png")
	TacleImageScale(totalpath, 820, "")
	//TacleTumbnail(totalpath,100, 100)
}

func (c *ArticleController)HTArticleDushuShort() {
	if c.Data["utype"].(int) != 10 {
		Message_noauto(&c.Controller, "", "权限错误", "", false)
	}
	uid := c.GetSession("uid").(int)
	user := models.Users{Id:uid}
	if err := htmodels.HTUsersGetDetail(&user); err != nil {
		Message_noauto(&c.Controller, "", "read user error", "", false)
	}
	article := models.Article{CityId:user.CityId}
	if err := htmodels.HTArticleGetDushuByCity(&article); err != nil {
		Message_noauto(&c.Controller, "", "read article error", "", false)
	}
	c.Data["Article"] = &article
	c.TplName = "dushu_detail.html"
}

func tacleArticlePermission(c *ArticleController, level int) {
	uri := c.Ctx.Request.RequestURI
	if strings.Index(uri, "?") != -1 {
		uri = uri[:strings.Index(uri, "?")]
	}
	if strings.Index(uri, "changestatus") != -1 {
		if level < 100 {
			Json_Message(&c.Controller, 0, "更改失败")
		}
	}
	return

	if strings.Index(uri, "list") != -1 {

	}
	if strings.Index(uri, "detail") != -1 {

	}

	if strings.Index(uri, "update") != -1 {
		ArticleType, _ := c.GetInt("ArticleType")
		Status, _ := c.GetInt("Status")
		if ArticleType == 0 && Status == 0 {

		}
	}
	if strings.Index(uri, "add") != -1 {
		ArticleType, _ := c.GetInt("ArticleType")
		Status, _ := c.GetInt("Status")
		if ArticleType == 0 && Status == 0 {

		}
	}
}

func tacleArticleMode() {

}

func tacleArticleStatus(c *ArticleController, laststatus int, currentstatus int, ArticleType int, userlevel int, userid int, Article *models.Article) int {
	if tacleDeny(c, laststatus, currentstatus, ArticleType, userlevel, Article) != 0 {
		return 1
	}
	if userlevel >= 100 {
		if laststatus != 3 {
			htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"文章《" + Article.Title + "》审核通过", ArticleId:Article.Id, LogTime:time.Now(), LogType:htmodels.LogType_ArticlePublish, Status:0})
			message := models.Messages{ReceiveId:userid, SendId:c.GetSession("uid").(int), MessagesTime:time.Now(), Type:6, MesageStatus:0, Addonfileds1:"恭喜您，您的文章《" + Article.Title + "》已通过审核并发布啦！"}
			user := models.Users{Id:userid}
			if err := htmodels.AddMarkOfCaculate(&user, htmodels.PublishMark); err != nil {
				fmt.Printf("add mark error when publish for user:%d", userid)
			}
			SendMessage(&message)
			return 3
		}
		return currentstatus
	}
	//读书会介绍更新特殊处理
	if ArticleType == 2 {
		return currentstatus
	}

	if ArticleType == 1 || ArticleType == 3 {
		return currentstatus
	}

	if inPermissionA(ArticleType) {
		if userlevel == 0 || userlevel == 1 {
			Message(&c.Controller, "", "权限受限,即将返回！", "", true)
		}
		if userlevel == 10 {
			if laststatus == 0 || laststatus == 1 {
				htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), ArticleId:Article.Id, Body:"文章《" + Article.Title + "》审核通过", LogTime:time.Now(), LogType:htmodels.LogType_ArticlePublish, Status:0})
				user := models.Users{Id:userid}
				if err := htmodels.AddMarkOfCaculate(&user, htmodels.PublishMark); err != nil {
					fmt.Printf("add mark error when publish for user:%d", userid)
				}
				message := models.Messages{ReceiveId:userid, SendId:c.GetSession("uid").(int), MessagesTime:time.Now(), Type:6, MesageStatus:0, Addonfileds1:"恭喜您，您的文章《" + Article.Title + "》已通过审核并发布啦！"}
				SendMessage(&message)
				return 3
			}
			if laststatus == 3 {
				return laststatus
			}
		}
		if userlevel == 2 {
			if laststatus == 1 {
				return 0
			}
		}
	}

	if inPermissionB(ArticleType) {
		if userlevel == 1 {
			if laststatus == 1 {
				return 0
			}
		}
		if userlevel >= 2 {
			if laststatus == 1 || laststatus == 0 {
				htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), ArticleId:Article.Id, Body:"文章《" + Article.Title + "》审核通过", LogTime:time.Now(), LogType:htmodels.LogType_ArticlePublish, Status:0})
				user := models.Users{Id:userid}
				if err := htmodels.AddMarkOfCaculate(&user, htmodels.PublishMark); err != nil {
					fmt.Printf("add mark error when publish for user:%d", userid)
				}
				message := models.Messages{ReceiveId:userid, SendId:c.GetSession("uid").(int), MessagesTime:time.Now(), Type:6, MesageStatus:0, Addonfileds1:"恭喜您，您的文章《" + Article.Title + "》已通过审核并已发布"}
				SendMessage(&message)
				return 3
			}
			if laststatus == 3 {
				return laststatus
			}
		}
	}
	Message(&c.Controller, "", "操作受限,即将返回！", "", true)
	return 0
}

func tacleDeny(c *ArticleController, laststatus int, currentstatus int, ArticleType int, userlevel int, Article *models.Article) int {
	deny := c.GetString("deny")
	if deny != "denied" {
		return 0
	}
	if inPermissionA(ArticleType) {
		if userlevel == 10 || userlevel == 1000 || userlevel == 100 {
			htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"文章《" + Article.Title + "》审核未通过", LogTime:time.Now(), LogType:htmodels.LogType_ArticleDeny, Status:0})
			message := models.Messages{ReceiveId:Article.UserId, SendId:c.GetSession("uid").(int), MessagesTime:time.Now(), Type:6, MesageStatus:0, Addonfileds1:"抱歉，您的文章《" + Article.Title + "》审核未通过，请在未审核中查看批注"}
			SendMessage(&message)
			return 1
		}
	}
	if inPermissionB(ArticleType) {
		if userlevel >= 2 {
			htmodels.InsertLog(&models.SQLLogs{UserId:c.GetSession("uid").(int), UserName:c.GetSession("name").(string), Body:"文章《" + Article.Title + "》审核未通过", LogTime:time.Now(), LogType:htmodels.LogType_ArticleDeny, Status:0})
			message := models.Messages{ReceiveId:Article.UserId, SendId:c.GetSession("uid").(int), MessagesTime:time.Now(), Type:6, MesageStatus:0, Addonfileds1:"抱歉，您的文章《" + Article.Title + "》审核未通过，请在未审核中查看批注"}
			SendMessage(&message)
			return 1
		}
	}
	Message(&c.Controller, "", "操作受限(deny),即将返回！", "", true)
	return 0
}

//type
//0 注册用户
//1 VIP用户
//2 地区助理
//10 地区管理员
//100 分权管理员
//1000 超级管理员

func getSubmitText(ArticleType int, status int, level int) string {
	if level >= 100 {
		if status < 3 {
			return "发布"
		}
		return "保存"
	}
	if inPermissionA(ArticleType) {
		if (status == 0 || status == 1) && level == 10 {
			return "发布"
		}
		if (status == 1) && level == 2 {
			return "重新提交"
		}
		if (status == 3) && level >= 10 {
			return "更新"
		}
		return "faultstatus"
	}
	if inPermissionB(ArticleType) {
		if (status == 0 || status == 1)&& level >= 2 {
			return "发布"
		}
		if (status == 1) || level == 1 {
			return "重新提交"
		}
		if (status == 3) && level >= 2 {
			return "更新"
		}
		return "faultstatus"
	}
	return "faultstatus"
}

func inPermissionA(ArticleType int) bool {
	if ArticleType == 0 || ArticleType == 2 || ArticleType == 4 || ArticleType == 5 || ArticleType == 6 || ArticleType == 31 {
		return true
	}
	return false
}

func inPermissionB(ArticleType int) bool {
	if ArticleType == 7 || ArticleType == 8 {
		return true
	}
	return false
}

//type
//0 活动咨询
//1 作品选登
//2 天使风采
//3 读书会简介
//4 读书会活动
//5 书香讲堂
//6 天下书坊
//7 家生活
//8 书坊创意设计
//7 天使书坊
//8 会员风采
//31 书香朗读